#!/bin/bash

# 日志输出
LOG_FILE="/var/log/init-mq.log"
exec > >(tee -a "$LOG_FILE") 2>&1
echo "脚本开始运行：$(date)"

# 检查 Java 环境
if ! command -v java &> /dev/null; then
  echo "未检测到 Java 环境，请安装 Java 后再运行此脚本。"
  exit 1
else
  echo "检测到 Java 环境：$(java -version 2>&1 | head -n 1)"
fi

# 设置下载链接和文件名
ROCKETMQ_URL="http://oss.wuyou.run/software/rocketmq/rocketmq-4.9.3.tar.gz"
ROCKETMQ_TAR="rocketmq-4.9.3.tar.gz"

# 检查并下载 RocketMQ 安装包
if [ ! -f "$ROCKETMQ_TAR" ]; then
  echo "$ROCKETMQ_TAR 文件不存在，开始下载..."
  if ! wget "$ROCKETMQ_URL" -O "$ROCKETMQ_TAR"; then
    echo "下载失败，请检查网络连接或下载链接是否正确。"
    exit 1
  fi
  echo "下载成功。"
else
  echo "$ROCKETMQ_TAR 文件已存在，跳过下载。"
fi

# 解压 RocketMQ 安装包
echo "正在解压 $ROCKETMQ_TAR 到 /data/rocketmq..."
mkdir -p /data/rocketmq
if ! tar zxf "$ROCKETMQ_TAR" -C /data/rocketmq --strip-components=1; then
  echo "解压失败，请检查 $ROCKETMQ_TAR 文件是否完整或是否有权限。"
  exit 1
fi
echo "解压成功。"

# 获取主机IP并匹配集群配置
HOST_IP=$(hostname -I | awk '{for(i=1;i<=NF;i++) if ($i !~ /^127\./) {print $i; exit}}')
declare -A CLUSTER_MAP=(
  ["172.36.133.107"]="broker-a:0:SYNC_MASTER"
  ["172.36.137.10"]="broker-a:1:SLAVE"
  ["172.36.135.239"]="broker-b:0:SYNC_MASTER"
  ["172.36.132.38"]="broker-b:1:SLAVE"
)

if [ -z "${CLUSTER_MAP[$HOST_IP]}" ]; then
  echo "未找到匹配的集群配置，当前IP：$HOST_IP"
  exit 1
fi

IFS=':' read -ra CONFIG <<< "${CLUSTER_MAP[$HOST_IP]}"
BROKER_NAME=${CONFIG[0]}
BROKER_ID=${CONFIG[1]}
BROKER_ROLE=${CONFIG[2]}

echo "当前节点配置："
echo "  IP: $HOST_IP"
echo "  Broker名称: $BROKER_NAME"
echo "  BrokerID: $BROKER_ID"
echo "  节点角色: $BROKER_ROLE"

# 设置公共参数
ROCKETMQ_HOME="/data/rocketmq"
CONF_DIR="$ROCKETMQ_HOME/conf/2m-2s-sync"
NAMESRV_ADDR="172.36.133.107:9876;172.36.137.10:9876;172.36.135.239:9876;172.36.132.38:9876"

# 检查端口冲突
check_port() {
  if netstat -tuln | grep -q ":$1 "; then
    echo "端口冲突：$1"
    exit 1
  fi
}

check_port 9876   # NameServer端口
check_port 10911  # Broker监听端口

# 创建存储目录
STORE_DIR="$ROCKETMQ_HOME/rocketmqStore/$BROKER_NAME"
mkdir -p "$STORE_DIR"

# 生成配置文件
CONFIG_FILE="$CONF_DIR/$BROKER_NAME.properties"
cat > "$CONFIG_FILE" << EOF
brokerClusterName=DefaultCluster
brokerName=$BROKER_NAME
brokerId=$BROKER_ID
deleteWhen=04
fileReservedTime=48
brokerRole=$BROKER_ROLE
flushDiskType=ASYNC_FLUSH
brokerIP1=$HOST_IP
listenPort=10911
storePathRootDir=$STORE_DIR
namesrvAddr=$NAMESRV_ADDR
EOF

echo "配置文件生成完成：$CONFIG_FILE"

# 设置启动脚本
START_SCRIPT="$ROCKETMQ_HOME/start.sh"
cat > "$START_SCRIPT" << EOF
#!/bin/bash
# 启动NameServer
nohup sh $ROCKETMQ_HOME/bin/mqnamesrv &

# 启动Broker
nohup sh $ROCKETMQ_HOME/bin/mqbroker -c $CONFIG_FILE > /dev/null &
EOF

chmod +x "$START_SCRIPT"
echo "启动脚本已生成：$START_SCRIPT"

echo "脚本运行完成：$(date)"
echo "请手动执行启动脚本：$START_SCRIPT"